#include "tcputils.h"
#include <QDebug>
#include <QHostAddress>

tcputils::tcputils( QObject* parent ) : QObject( parent ) {}

tcputils::~tcputils() {
    m_timer->stop();
    if ( mSocket != Q_NULLPTR ) { mSocket->close(); }
    delete m_timer;
    delete mSocket;
}

bool tcputils::getConnectStatus() {
    return connectStatus;
}

void tcputils::init() {
    m_timer = new QTimer();
    mSocket = new QTcpSocket();
    connect( mSocket, SIGNAL( connected() ), this, SLOT( onConnected() ) );
    connect( mSocket, SIGNAL( disconnected() ), this, SLOT( onDisConnected() ) );
    connect( mSocket, SIGNAL( readyRead() ), this, SLOT( onTextReceived() ) );
    connect( m_timer, SIGNAL( timeout() ), this, SLOT( reconnect() ), Qt::AutoConnection );
    connect( mSocket, SIGNAL( error( QAbstractSocket::SocketError ) ), this, SLOT( onConnecterror( QAbstractSocket::SocketError ) ) );
}

void tcputils::close() {
    emit sigSendTips( "关闭连接!" );
    connectStatus = false;
    m_timer->stop();
    mSocket->close();
}
void tcputils::createDataRecv( const QString& ip, const int& id ) {
    serverIP = QString( ip );
    agvId    = QString::number( id );
    if ( mSocket != Q_NULLPTR ) { mSocket->close(); }
    mSocket->connectToHost( serverIP, serverPort );
    emit sigSendTips( "CONNECT" );
}

void tcputils::reconnect()  //重新连接
{
    mSocket->close();
    mSocket->connectToHost( serverIP, serverPort );
}

void tcputils::onConnected() {
    connectStatus = true;
    m_timer->stop();
    emit    sigSendTips( "连接成功! IP:" + serverIP );
    QString loginmsg = "username=no" + agvId + "&src=agv";
    mSocket->write( loginmsg.toUtf8() );
}

void tcputils::onTextReceived() {
    QString msg = mSocket->readAll();
    if ( msg == QString::fromLocal8Bit( "1" ) ) return;
    emit sigSendTips( msg );
}

void tcputils::onDisConnected() {
    emit sigSendTips( "连接失败，尝试重新连接..." );
    connectStatus = false;
    m_timer->start( 3000 ); /*-<当连接失败时，触发重连计时器，设置计数周期为3秒 */
}

void tcputils::onConnecterror( QAbstractSocket::SocketError& state ) {
    Q_UNUSED( state )
    emit sigSendTips( "CONNECT" );
    connectStatus = false;
    m_timer->start( 3000 ); /*-<当连接失败时，触发重连计时器，设置计数周期为3秒 */
}
